<template>
  <div class="box">
    <h1>瓦斯单单博客管理系统</h1>
    <el-form
      :model="LoginForm"
      status-icon
      :rules="rules"
      ref="loginForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" prop="name">
        <el-input v-model="LoginForm.name"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input type="password" v-model="LoginForm.pass"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "LoginPart",
  data() {
    return {
      LoginForm: {
        name: "",
        pass: "",
      },
      rules: {
        name: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        pass: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  methods: {
    login() {
      this.$refs.loginForm.validate((v) => {
        if (v) {
          this.axios
            .post(
              "http://127.0.0.1:8080/Login/login",
              {},
              {
                params: this.LoginForm,
                headers: {
                  "content-type": "application/x-www-form-urlencoded",
                },
              }
            )
            .then((res) => {
              if (res.data.code === 200) {
                this.$message({
                  message: "登录成功",
                  type: "success",
                });
                localStorage.setItem("token", res.data.token);
                localStorage.setItem("username", res.data.username);
                this.$router.push("/home");
              }
              if (res.data.code === 401) {
                this.$message.error("用户名或密码错误");
              }
            });
        }
      });
    },
  },
  mounted(){
    this.axios
      .post(
        "http://127.0.0.1:8080/Login/token",
        {},
        {
          headers: {
            "content-type": "application/x-www-form-urlencoded",
          },
          params: {
            Authorization: `bearer ${localStorage.getItem("token")}`,
          },
        }
      )
      .then((res) => {
        if(res.data.code === 200){
          this.$router.push('/home');
        }
      })
  }
};
</script>

<style scoped>
.box {
  width: 500px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -60%);
}
h1 {
  text-align: center;
}
</style>